var express = require("express");
var router = express.Router();

var { data, types } = require("./product");
// console.log(a);

// const data = require("../data/data");

// const types = require("../data/types");

let type = 8;

// 分类页面分类项
router.get("/types", function (req, res, next) {
  res.json({
    success: true,
    data: types,
  });
});

router.post("/types/add", function (req, res, next) {
  const token = req.headers.token;
  const { title } = req.body;

  if (token === "821cef") {
    types.push({
      type,
      title,
    });
    type++;
    if (title) {
      res.json({
        success: true,
        msg: "添加成功",
      });
    } else {
      res.json({
        success: false,
        msg: "参数错误",
      });
    }
  } else {
    res.json({
      success: false,
      msg: "token错误",
    });
  }
});

router.post("/types/remove", function (req, res, next) {
  const token = req.headers.token;
  const { type } = req.body;

  if (token === "821cef") {
    if (type) {
      types = types.filter((item) => item.type != type);
      res.json({
        success: true,
        msg: "删除成功",
      });
    } else {
      res.json({
        success: false,
        msg: "参数错误",
      });
    }
  } else {
    res.json({
      success: false,
      msg: "token错误",
    });
  }
});

router.post("/types/edit", function (req, res, next) {
  const token = req.headers.token;
  const { type, title } = req.body;

  if (token === "821cef") {
    if (type && title) {
      types.forEach((item) => {
        if (item.type == type) {
          item.title = title;
        }
      });
      res.json({
        success: true,
        msg: "修改成功",
      });
    } else {
      res.json({
        success: false,
        msg: "参数错误",
      });
    }
  } else {
    res.json({
      success: false,
      msg: "token错误",
    });
  }
});

// 分类页面分类数据
router.get("/list", function (req, res, next) {
  const { type } = req.query;
  if (type) {
    // console.log(data);
    // console.log(type);

    const typeList = data.filter((item) => item.type === +type);
    res.json({
      success: true,
      data: typeList,
    });
  } else {
    res.json({
      success: false,
      msg: "参数错误",
    });
  }
});

module.exports = { classifyRouter: router, types };
